﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.Cecil;
using NDasm.Core.UI.Base;
using NDasm.Core.UI.MethodDasm;
using NDasm.Core.UI.Tree;

namespace NDasm.Core.UI
{
    public class DasmViewModel : ViewModel, IDisposable
    {
        public DasmViewModel(ModuleDefinition module)
        {
            AssemblyTree = new AssemblyTreeViewModel(module);
            AssemblyTree.PropertyChanged += (s, a) =>
                                                {
                                                    if (a.PropertyName == "SelectedItem")
                                                        UpdateMethodModel();
                                                };
        }        

        public AssemblyTreeViewModel AssemblyTree { get; private set; }

        private MethodDasmViewModel methodDasm;        
        public MethodDasmViewModel MethodDasm 
        {
            get { return methodDasm; }
            private set
            {
                methodDasm = value;
                NotifyPropertyChanged(() => MethodDasm);
            }
        }

        public void ProcessMember(IMemberDefinition member)
        {
            AssemblyTree.SelectMember(member);
        }

        private void UpdateMethodModel()
        {
            if (AssemblyTree.SelectedItem == null)
            {
                MethodDasm = null;
                return;
            }                
            var methodNode = AssemblyTree.SelectedItem as MethodNodeViewModel;
            MethodDasm = methodNode != null ? new MethodDasmViewModel((MethodDefinition)methodNode.Member) : null;
        }

        public void Dispose()
        {
            AssemblyTree.Dispose();
        }
    }
}
